GBML manual / Maths

clamp_int

The same as clamp, for whole numbers: value pushed back between lo and hi if it has wandered outside them, and the answer is a whole number. Use this one whenever the thing you are clamping is counted rather than measured - a slot number, a level, a lives count - so it stays a whole number.

Syntax

clamp_int(value, lo, hi) -> int

Arguments

NameType
valueint
loint
hiint

Returns

int

Description

The same as clamp, for whole numbers: value pushed back between lo and hi if it has wandered outside either one - and the answer is a whole number.

Reach for this one whenever the thing you are clamping is counted rather than measured: a slot number, a level, a lives count, which row of a menu is picked. Use clamp for things that are measured - a position, a speed, a volume.

Example

var band = int_floor(x / 32);
band = clamp_int(band, 1, 6);

Works out which band this object is standing in, then keeps that inside the six bands that exist - and keeps it a whole number, so it can still be handed to anything that wants one.

Why there are two of these

clamp and clamp_int do the same arithmetic. They differ in the type of the answer, and that difference is worth a function of its own because of what goes wrong without it.

clamp hands back a real. So this line:

band = clamp(band, 1, 6);          <- the trap: this is NOT what you want here

turns band into a real - the value is still 3, but the kind of number has changed. Nothing complains there. The complaint arrives later, somewhere else, wherever band is next handed to something that wants a whole number:

Argument 3 to `rolling_text` should be an int, but this is a real.

That error points at a line that looks perfectly fine, in a file that may be nowhere near the assignment that caused it. Written with clamp_int, it cannot happen.

lo and hi can be given in either order

A reversed pair (lo bigger than hi) is swapped before anything else happens, so clamp_int always returns a value between whichever two bounds were actually given - never a crash, and never a wrong answer for getting the order backwards. The same promise clamp makes.

Cost

A couple of comparisons - cheap enough for every frame.

On the GBA

clamp and clamp_int differ in TYPE, not in arithmetic. clamp hands back a real, so `n = clamp(n, 1, 6)` turns a whole number into a real one, and the next place that wants a whole number refuses it - usually somewhere else entirely, which makes it a puzzle. clamp_int hands back a whole number, so it cannot happen. lo and hi may be given in either order, exactly as clamp allows; a reversed pair is swapped first. A couple of comparisons, cheap enough for every frame.

See also: clampminmaxint_floormin_intmax_int